package au.com.bus4u.controller;


import au.com.bus4u.exception.PseudoLoginSuccessException;
import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.utils.JsonResult;
import au.com.bus4u.utils.PageData;
import au.com.bus4u.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.util.logging.Logger;

/**
 * 所用控制器类的父类
 */
public abstract class BaseController {
	
	protected static final String SESSION_UID="uid";
	protected static final String SESSION_USERNAME="username";
	
	protected static final Integer SUCCESS=0;
	// 静态常量的命名：所有字母都大写，单词用_隔开，尽量说明白，不要嫌长
	protected static final Integer ERROR_USERNAME_DUPLICATE=30;
	/**
	 * 对控制器中的异常进行统一处理
	 * @param e 异常对象
	 * @return JsonResult封装响应信息
	 */
	@ExceptionHandler({Exception.class})
	@ResponseBody
	public JsonResult<Void> handlerException(Throwable e){
		// 根据不同异常的类型提供不同的处理方式
		// 现在的处理方式是根据不同的类型，返回不同的状态码
		JsonResult<Void> jr=new JsonResult<>(e.getMessage());
		
		if(e instanceof AccessDeniedException) {
			jr.setCode(1);
		}else if(e instanceof CannotGetJdbcConnectionException) {
			jr.setCode(1);
			jr.setMsg("数据库连接异常");
		}else if(e instanceof UnknownAccountException) {
			jr.setCode(1);
			jr.setMsg("用户名不存在");
		}else if(e instanceof IncorrectCredentialsException) {
			jr.setCode(1);
			jr.setMsg("密码错误");
		}else if(e instanceof PseudoLoginSuccessException) {
			jr.setCode(10);
			jr.setMsg("伪登陆成功!");
		}else if(e instanceof LockedAccountException) {
			jr.setCode(1);
		}else if(e instanceof UnauthorizedException) {
			jr.setCode(5);
			jr.setMsg("此账号无此功能操作权限!");
		}else if(e instanceof ServiceException) {
			jr.setCode(1);
		}else if(e instanceof ServletException) {
			jr.setCode(500);
			jr.setMsg("ServletException");
		}else if(e instanceof NullPointerException) {
			jr.setCode(500);
			jr.setMsg("NullPointerException");
		}else if(e instanceof IOException) {
			jr.setCode(500);
			jr.setMsg("IOException");
		}

		//ServletException, IOException
		return jr;
	}
	
	public String getUsernameFromSession(HttpSession session) {
		// 从session中获取username
		return session.getAttribute(SESSION_USERNAME).toString();
	}
	
	public Integer getUidFromSession(HttpSession session) {
		// 从session中获取uid
		return Integer.valueOf(session.getAttribute(SESSION_UID).toString());
	}
	
	public PageData getPageData(){
		return new PageData(getRequest());
	}

	public PageData getCurrentUser(){
		return (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
	}
	public String getCurrentUserID(){
		PageData pd = (PageData) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
		String user_id = pd.get("user_id").toString();
		return user_id;

	}

	public HttpServletRequest getRequest() {

		if (RequestContextHolder.getRequestAttributes() == null) {
			return null;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;

	}

	public static void logBefore(Logger logger, String interfaceName) {
		logger.info("");
		logger.info("start");
		logger.info(interfaceName);

	}


	public static void logAfter(Logger logger) {
		logger.info("end");
		logger.info("");

	}
	public String get32UUID() {
        return UuidUtil.get32UUID();
    }


	/**
	 * 传递全部页面信息返回需要的分页page数据
	 * @param pageInfo
	 * @return
	 */
	public PageData getPage(PageInfo<PageData> pageInfo){
		PageData page = new PageData();
		page.put("endRow",pageInfo.getEndRow());
		page.put("hasNextPage",pageInfo.isHasNextPage());
		page.put("hasPreviousPage",pageInfo.isHasPreviousPage());
		page.put("isFirstPage",pageInfo.isIsFirstPage());
		page.put("isLastPage",pageInfo.isIsLastPage());
		page.put("navigateFirstPage",pageInfo.getNavigateFirstPage());
		page.put("navigateLastPage",pageInfo.getNavigateLastPage());
		page.put("navigatepageNums",pageInfo.getNavigatepageNums());
		page.put("pages",pageInfo.getPages());
		page.put("size",pageInfo.getSize());
		page.put("navigatePages",pageInfo.getNavigatePages());
		page.put("nextPage",pageInfo.getNextPage());
		page.put("pageNum",pageInfo.getPageNum());
		page.put("pageSize",pageInfo.getPageSize());
		page.put("prePage",pageInfo.getPrePage());
		page.put("startRow",pageInfo.getStartRow());
		page.put("total",pageInfo.getTotal());
		return page;
	}


	/**
	 * pageNum - 第几页
	 * pageSize - 每页显示条数
	 * 从请求中获取页面传递而来的参数pageNum和pageSize
	 * 如果pageNum为空，则设置默认值为1	pageSize默认值为10
	 *
	 */
	public void setPageHelperStartPage(){
		PageData pageData = getPageData();
		Integer pageNum = 1;
		Integer pageSize = 10;
//		Object pageNumObj = pageData.get("pageNum");
//		Object pageSizeObj = pageData.get("pageSize");
		Object pageNumObj = pageData.get("page");
		Object pageSizeObj = pageData.get("limit");
		if (pageNumObj != null) {
//			System.out.println("pageNumObj = " + pageNumObj);
			pageNum = Integer.parseInt(pageNumObj.toString());
		}

		if (pageSizeObj != null) {
//			System.out.println("pageSizeObj = " + pageSizeObj);
			pageSize = Integer.parseInt(pageSizeObj.toString());
		}

		PageHelper.startPage(pageNum , pageSize);

	}


}




